package core;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

import authentication.AuthenticationManager;
import infrastructure.exceptions.BaseServerException;
import infrastructure.exceptions.BaseServerRuntimeException;
import infrastructure.exceptions.ServerFataError;
import remote.RemoteInvocation;
import remote.Session;

public class OperationWrapper {

	
	public static Object  doOperation(RemoteInvocation invocationParams) throws ServerFataError,BaseServerException,BaseServerRuntimeException{
		
		try{
			Session operationSession = 
				AuthenticationManager.getInstance().getSession(
						new Session.SessionId(invocationParams.getSessionID()));
			// Create constructor for the required class operation
			Constructor<?> ctor =  invocationParams.getInvocationClass().getConstructor(new Class<?>[]{Session.class});
			
			// create instance of the required .. 
			Object classToInvoke = ctor.newInstance(operationSession);
			
			// invoke required method 
			Object retVal = invocationParams.getMethod().invoke(classToInvoke, (Object[])invocationParams.getMethodParams());
			
			return retVal;

		}catch(NoSuchMethodException methodEx){
			throw new BaseServerRuntimeException("Invalid call");
		} catch (IllegalArgumentException e) {
			throw new BaseServerRuntimeException("Invalid call");
		} catch (InstantiationException e) {
			throw new BaseServerRuntimeException("Invalid call");
		} catch (IllegalAccessException e) {
			throw new BaseServerRuntimeException("Invalid call");
		} catch (InvocationTargetException e) {
			
			Throwable targetException = e.getCause();
			if (targetException instanceof BaseServerException){
				throw (BaseServerException)targetException;
			}else if (targetException instanceof BaseServerRuntimeException){
				throw (BaseServerRuntimeException)targetException;
			}else if (targetException instanceof ServerFataError){
				throw (ServerFataError)targetException;
			}else{
				throw new ServerFataError("Unexpected exception",targetException);
			}
		}		
	}
	
	 
}
